package com.atguigu.flink.worldcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;


public class WorldCountBoundBatch {

    public static void main(String[] args) throws Exception {

        //TODO 创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //TODO 从指定位置读数据
        DataSource<String> ds = env.readTextFile("input/wc.txt");

        //TODO 转换数据格式
        FlatMapOperator<String, Tuple2<String, Long>> wordAndOne  = ds.flatMap(

                new FlatMapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public void flatMap(String line, Collector<Tuple2<String, Long>> collector) throws Exception {

                        String[] words = line.split(" ");

                        for (String word : words) {

                            collector.collect(new Tuple2<>(word, 1L));

                        }
                    }
                }
        );

        UnsortedGrouping<Tuple2<String, Long>> wordAndOneUG = wordAndOne.groupBy(0);

        wordAndOneUG.sum(1).print();
    }
}
